package com.yjb.auth.component;

import com.yjb.auth.entity.RoleMenuRel;
import com.yjb.auth.entity.SysMenu;
import com.yjb.auth.entity.SysUser;
import com.yjb.auth.service.RoleMenuRelService;
import com.yjb.auth.service.SysMenuService;
import com.yjb.auth.service.SysUserService;
import com.yjb.auth.service.UserRoleRelService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    SysUserService userService;
    @Autowired
    RoleMenuRelService rolePermissionService;
    @Autowired
    SysMenuService permissionService;
    @Autowired
    UserRoleRelService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String usrename) throws UsernameNotFoundException {
        SysUser sysUser = userService.getByUsername(usrename);
        if (sysUser != null) {
            List<GrantedAuthority> grantedAuthoritys = Lists.newArrayList();

            List<RoleMenuRel> sysRolePermissionList = rolePermissionService.listByUserId(sysUser.getId());
            List<Integer> permisssionIdList = sysRolePermissionList.stream().map(RoleMenuRel::getMenuId).collect(Collectors.toList());
            List<SysMenu> permissionList = permissionService.listByIds(permisssionIdList);
            permissionList.forEach(
                    permission -> {
                        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getMenuName());
                        grantedAuthoritys.add(grantedAuthority);
                    }
            );
            System.out.println(grantedAuthoritys);
            return new User(sysUser.getUsername(), sysUser.getPassword(), grantedAuthoritys);
        }
        return null;
    }
}
